package com.bustle.commons.http;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.http.entity.StringEntity;

import com.bustle.commons.Converter;

public class TypeToXmlHttpConverter<Type> implements Converter<Type, StringEntity>
{
  public TypeToXmlHttpConverter(Class<Type> aClass)
  {
    type = aClass;
  }

  @Override
  public StringEntity convert(Type aSource)
  {
    try
    {
      JAXBContext context = JAXBContext.newInstance(type);
      Marshaller marshaller = context.createMarshaller();
      StringWriter stringWriter = new StringWriter();
      marshaller.marshal(aSource, stringWriter);
      StringEntity stringEntity = new StringEntity(stringWriter.toString());
      stringEntity.setContentType("application/xml");
      return stringEntity;
    }
    catch (JAXBException | UnsupportedEncodingException anException)
    {
      anException.printStackTrace();
    }
    return null;
  }

  protected Class<Type> type;
}
